package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crb2btradecenter.service.CrB2bTradeCenterService;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.otsapplicationappsdk.saleorderlist.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.saleorderlist.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.saleorderlist.service.SaleOrderListService;
import com.epoch.app.crb2btradecenter.dto.response.OrderPageQueryResponse;
import com.epoch.app.crb2btradecenter.model.dto.PageQueryOrderEsListRequest;
import com.epoch.app.crplatformenhance.model.dto.QueryEnumValuesRequest;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SaleOrderListV2ServiceImpl implements SaleOrderListService {
    public static final String PATTERN_DATE_TIME_MIDDLE_LINE = "yyyy.MM.dd HH:mm:ss";
    public static final String PATTERN_DATE_TIME = "yyyy-MM-dd HH:mm:ss";

    private static Log log = Log.getLogger(SaleOrderListV2ServiceImpl.class);
//    @Autowired
//    @Qualifier("OrderQueryService")
//    private OrderQueryService orderQueryService;

//    @Autowired
//    private OtsPlatformEnhanceService otsPlatformEnhanceService;
    @Autowired
    private CrPlatformEnhanceService otsPlatformEnhanceService;

//    @Autowired
//    private OtsB2bTradeCenterService otsB2bTradeCenterService;
    @Autowired
    private CrB2bTradeCenterService otsB2bTradeCenterService;

    @Override
    public Object render(RenderRequest renderRequest) {
        PageQueryOrderEsListRequest orderPageQueryRequest = new PageQueryOrderEsListRequest();

        if (null == renderRequest.getCurrentPage()) {
            renderRequest.setCurrentPage(1);
        }
        Integer page = renderRequest.getCurrentPage();
        Integer size = renderRequest.getSize();

        Integer start = (page - 1) * size;

        orderPageQueryRequest.setStart(start);
        orderPageQueryRequest.setLimit(size);
        orderPageQueryRequest.setMainStatusList(Arrays.asList("-1","1","2","3","4","5","7","11","12","13","14"));

        orderPageQueryRequest.setOrderTag("normal");

        //Result<List<OrderPageQueryResponse>> listResult = orderQueryService.pageQueryOrderListES(orderPageQueryRequest);
        Result<List<OrderPageQueryResponse>> listResult = otsB2bTradeCenterService.querySaleOrderList(orderPageQueryRequest);
        //单据类型
        List<Info> orderTypeList = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
            setCode("saleOrderTag");
        }}))).getString("result"), List.class);


        Map<String, Object> backs = new HashMap<>();
        backs.put("list", listResult.getResult());
        backs.put("total", new Double(Math.ceil((double) listResult.getTotal() / size)).intValue());
        backs.put("page", page);
        backs.put("size", size);
        backs.put("planOrderTypeList", Objects.isNull(orderTypeList) ? new ArrayList<>() : orderTypeList);
        return Result.success(backs);
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        log.info(JSONObject.toJSONString(asyncRequest));
        //筛选条件
        List<String> gmtCreate=new ArrayList<>();
        List<String> orderType = new ArrayList<>();

        //下拉选中
        String address = null;
        String customer = null;

        //输入的单号
        String orderId = null;

        //分页参数
        Integer currentPage = 1;
        Integer pageSize = 10;

        //TAB页切换
        Integer status = null;

        JSONObject requestInput = JSONObject.parseObject(JSONObject.toJSONString(asyncRequest.getRequestInput())).getJSONObject("fields").getJSONObject("otherFields");
        log.info(JSONObject.toJSONString(requestInput));

        //筛选条件 日期筛选和单据类型筛选
        if (Objects.nonNull(requestInput.getJSONObject("filterOptions"))) {
            List<PlanOrderListV2ServiceImpl.Group> groups = requestInput.getJSONObject("filterOptions").getJSONArray("group").toJavaList(PlanOrderListV2ServiceImpl.Group.class);
            for (PlanOrderListV2ServiceImpl.Group group : groups) {
                if ("date".equalsIgnoreCase(group.getType())) {
                    List<PlanOrderListV2ServiceImpl.DataSource> dataSource = group.getDataSource();
                    for (PlanOrderListV2ServiceImpl.DataSource source : dataSource) {
                        if ("startTime".equalsIgnoreCase(source.getKey())) {
                            gmtCreate.add(0,getStringDate(source.getValue()));
                        }
                        if ("endTime".equalsIgnoreCase(source.getKey())) {
                            gmtCreate.add(getStringDate((Objects.nonNull(source.getValue())&&StringUtils.isNotBlank(source.getValue()))?String.valueOf(Long.valueOf(source.getValue())+86399999l):""));
                        }
                    }

                }

                if ("tag".equalsIgnoreCase(group.getType())) {

                    List<PlanOrderListV2ServiceImpl.DataSource> dataSource = group.getDataSource();
                    for (PlanOrderListV2ServiceImpl.DataSource source : dataSource) {
                        if (true == source.getSelected() && !"ALL".equalsIgnoreCase(source.getValue())) {
                            orderType.add(source.getValue());
                        }
                    }

                }

            }
        }
        //判断客户或者地址是否被选中
        if (Objects.nonNull(requestInput.getJSONArray("selectOptions"))) {
            List<PlanOrderListV2ServiceImpl.Group> selectOptions = requestInput.getJSONArray("selectOptions").toJavaList(PlanOrderListV2ServiceImpl.Group.class);
            for (PlanOrderListV2ServiceImpl.Group selectOption : selectOptions) {
                if ("address".equalsIgnoreCase(selectOption.getKey())) {
                    JSONObject selected = selectOption.getSelected();
                    if (Objects.nonNull(selected)) {
                        address = selected.getString("addressCode");
                    }

                }
                if ("customer".equalsIgnoreCase(selectOption.getKey())) {
                    JSONObject selected = selectOption.getSelected();
                    if (Objects.nonNull(selected)) {
                        customer = selected.getString("code");
                    }

                }
            }
        }

        //订单id
        if (Objects.nonNull(requestInput.getString("orderId"))) {
            orderId = requestInput.getString("orderId");
        }


        //分页
        if (null!=requestInput.getInteger("currentPage")) {
            currentPage = requestInput.getInteger("currentPage");
        }

        if (Objects.nonNull(requestInput.getInteger("pageSize"))) {
            pageSize = requestInput.getInteger("pageSize");
        }

        //切换tab
        if (Objects.nonNull(requestInput.getInteger("status")) && 0 != requestInput.getInteger("status")) {
            status = requestInput.getInteger("status");
        }



        Integer start = (currentPage - 1) * pageSize;
        log.info("start::::"+start);
        log.info("currentPage::::"+currentPage);
        log.info("pageSize::::"+pageSize);
        PageQueryOrderEsListRequest orderPageQueryRequest = new PageQueryOrderEsListRequest();
        orderPageQueryRequest.setPage(currentPage);
        orderPageQueryRequest.setSize(pageSize);

        //
        if (Objects.nonNull(status) && 0 != status) {
            orderPageQueryRequest.setStatus(String.valueOf(status));
        } else {
            orderPageQueryRequest.setMainStatusList(Arrays.asList("-1","1","2","3","4","5","7","11","12","13","14"));
            status = 0;

        }
        //收货地址编码
        if (StringUtils.isNotBlank(address)) {
            orderPageQueryRequest.setDeliveryAddr(address);
        }
        //单据类型
        if (CollectionUtils.isNotEmpty(orderType)) {
            orderPageQueryRequest.setOrderTypeList(orderType);
        }

        //订单ID
        if (StringUtils.isNotBlank(orderId)) {
            orderPageQueryRequest.setOrderBizId(orderId);
        }

        //客户编码
        if (StringUtils.isNotBlank(customer)) {
            orderPageQueryRequest.setCustomerCode(customer);
        }


        if (Objects.nonNull(gmtCreate)&&CollectionUtils.isNotEmpty(gmtCreate)) {
            orderPageQueryRequest.setOrderTime(gmtCreate);
        }


        orderPageQueryRequest.setOrderTag("normal");

        log.info("async orderPageQueryRequest:"+JSONObject.toJSONString(orderPageQueryRequest));
       // Result<List<OrderPageQueryResponse>> listResult = orderQueryService.pageQueryOrderListES(orderPageQueryRequest);
        Result<List<OrderPageQueryResponse>> listResult = otsB2bTradeCenterService.querySaleOrderList(orderPageQueryRequest);
        log.info("async listResult:"+JSONObject.toJSONString(listResult));
        //单据类型
        List<Info> orderTypeList = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
            setCode("saleOrderTag");
        }}))).getString("result"), List.class);


        Map<String, Object> backs = new HashMap<>();
        backs.put("status", status);
        backs.put("list", listResult.getResult());
        backs.put("total", new Double(Math.ceil((double) listResult.getTotal() / pageSize)).intValue());
        backs.put("page", currentPage);
        if (currentPage > 1) {
            backs.put("reload", false);
        } else {
            backs.put("reload", true);
        }
        backs.put("size", pageSize);
        backs.put("planOrderTypeList", Objects.isNull(orderTypeList) ? new ArrayList<>() : orderTypeList);
        return Result.success(backs);
    }
    private String getStringDate(String timestamp){

        if (StringUtils.isBlank(timestamp)){
            return null;
        }
        Date date = new Date(Long.valueOf(timestamp));
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat(PATTERN_DATE_TIME);
        String format = simpleDateFormat.format(date);

        return format;
    }
    @Data
    static class Group {
        @JsonProperty("type")
        public String type;

        @JsonProperty("title")
        public String title;

        @JsonProperty("placeholder")
        public String placeholder;

        @JsonProperty("key")
        public String key;

        @JsonProperty("fetchUrl")
        public String fetchUrl;

        @JsonProperty("dataSource")
        public List<DataSource> dataSource;


    }

    @Data
    static class SelectOption {
        @JsonProperty("type")
        public String type;

        @JsonProperty("title")
        public String title;

        @JsonProperty("placeholder")
        public String placeholder;

        @JsonProperty("dataSource")
        public List<DataSource> dataSource;

    }

    @Data
    static class DataSource {
        @JsonProperty("label")
        public String label;

        @JsonProperty("key")
        public String key;

        @JsonProperty("value")
        public String value;

        @JsonProperty("selected")
        public Boolean selected;

    }

    @Data
    public static class Info {
        private String label;
        private String value;
    }
}

